import {
	ethers
} from "ethers";

export default class Web3Init {
	constructor({
		artifact = null,
		address = null,
		abi = null
	}) {
		this.meta = this.account = this.signer = this.web3 = null;
		this.artifact = artifact;
		//以下2种情况对应，后端开发人员直接给出合约地址与合约abi的情况（比如只给了json文件的abi部分）
		this.address = address;
		this.abi = abi;
		// 链接的url地址，有啥用暂时不清楚,在main.js中设置
		this.url = this.constructor.prototype.constructor.url;
	}
	init() {
		return new Promise((resolve, reject) => {
			if (window.ethereum) {
				// use MetaMask's provider
				this.web3 = new ethers.providers.Web3Provider(window.ethereum)
				window.ethereum.enable(); // get permission to access accounts
			} else {
				console.warn(
					"No web3 detected. Falling back to" + this.url +
					" . You should remove this fallback when you deploy live"
				);
				// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
				this.web3 = new ethers.providers.JsonRpcProvider(this.url);
				reject("No web3 detected. Falling back to" + this.url +
					" . You should remove this fallback when you deploy live")
			}
			this.start().then(res => {
				resolve(this)
			})

		})
	}
	async start() {
		const {
			web3
		} = this;
		try {
			// get contract instance
			const networkId = (await web3.getNetwork()).chainId;

			if (this.address === null) {
				const deployedNetwork = this.artifact.networks[networkId];
				this.address = deployedNetwork.address;
			}
			if (this.abi === null) {
				this.abi = this.artifact.abi;
			}
			this.signer = web3.getSigner()
			this.meta = new ethers.Contract(
				this.address,
				this.abi,
				web3
			).connect(this.signer);
			this.account = await this.signer.getAddress();
		} catch (error) {
			console.error(error);
			console.error("Could not connect to contract or chain.");
		}
	}



}